package 链表;


/**
 * https://leetcode.cn/problems/reverse-nodes-in-k-group/
 *
 * 题解：https://mp.weixin.qq.com/s?__biz=MzAxODQxMDM0Mw==&mid=2247493186&idx=1&sn=0197888f254f0f3afde11423a8dd6281&chksm=9bd4184aaca3915cc53135ca48c0c3b2695b6ce906a672a38d5ab27b675bf47cd18456d9a4d8&scene=178&cur_album_id=2165022824317485057#rd
 */
public class _25_K个一组翻转链表 {

    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || head.next == null) return null;

        ListNode a = head;
        ListNode b = head;

        for (int i = 0; i < k; i++) {
            if(b == null) return head;
            b = b.next;
        }

        ListNode result = reverse(a,b);
        a.next = reverseKGroup(b,k);
        return result;
    }


    private ListNode reverse(ListNode a,ListNode b) {
        ListNode pre = null;
        ListNode cur = a;
        ListNode nxt = a;

        while (cur != b) {
            nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }

        return pre;
    }
}
